﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;
using VideoSeller.Business.Data;
using VideoSeller.Business.Data.Entities;
using VideoSeller.Business.Data.Enums;
using System.Globalization;
using System.Threading;

namespace VideoSeller.Business.JavaScriptConverters
{
	public class OnlineContentConverter : JavaScriptConverter
	{
        private static CultureInfo _cinfo = null;
        public static CultureInfo cinfo
        {
            get
            {
                if (_cinfo == null)
                {
                    _cinfo = new CultureInfo("en-US");
                    _cinfo.NumberFormat.NumberDecimalSeparator = ".";
                }
                return _cinfo;
            }
        }
		public override IEnumerable<Type> SupportedTypes
		{
			get { return new[] { typeof(OnlineContentItem), typeof(OnlineContent) }; }
		}

		public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
		{
            //bool _RemoveAds = false;
			var item = new OnlineContentItem
				{
                    
					Name = dictionary["Name"].ToString(),
					Description = dictionary["Description"].ToString(),
					ThumbnailFileName = dictionary["ThumbnailFileName"].ToString(),
					ThumbnailFileUrl = dictionary["ThumbnailFileUrl"].ToString(),
					CamParam = dictionary["CamParam"].ToString(),
					BroadcastDescription = dictionary["BroadcastDescription"].ToString(),
					BroadcastType = dictionary["BroadcastType"].ToString() == "selfBroadcast" ? BroadcastType.Manually : BroadcastType.Automatically,
					Categories = new List<string>(dictionary["Categories"].ToString().Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries)),
					Culture = dictionary["SelectedCulture"].ToString(),
					Country = int.Parse(dictionary["SelectedCountry"].ToString()),
					Password = dictionary["Password"].ToString(),
					IsDraft = bool.Parse(dictionary["IsDraft"].ToString()),
                    AutoHistory = bool.Parse(dictionary["AutoHistory"].ToString()),
					RemoveAds = dictionary.ContainsKey("RemoveAds")? bool.Parse(dictionary["RemoveAds"].ToString()):(bool) false,
					CreatedContentId = int.Parse(dictionary["CreatedContentId"].ToString()),
                    QualityString = dictionary["QualityString"].ToString(),
                    MaxUsers = int.Parse(dictionary["ViewrCnt"].ToString()),
                    MaxHours = int.Parse(dictionary["MaxTime"].ToString()),
				
                    VideoContentType = (VideoContentType)Enum.Parse(typeof(VideoContentType), dictionary["VideoContentType"].ToString())
				};

			if (item.BroadcastType == BroadcastType.Manually && !string.IsNullOrEmpty(dictionary["ManualStartDate"].ToString()) && !string.IsNullOrEmpty(dictionary["ManualStartTime"].ToString()))
			{
				item.StartDateTime = DateTime.Parse(string.Format("{0} {1}", dictionary["ManualStartDate"], dictionary["ManualStartTime"]));
			}

			if (item.BroadcastType == BroadcastType.Automatically && !string.IsNullOrEmpty(dictionary["StartDate"].ToString()) && !string.IsNullOrEmpty(dictionary["StartTime"].ToString()))
			{
				item.StartDateTime = DateTime.Parse(string.Format("{0} {1}", dictionary["StartDate"], dictionary["StartTime"]));
			}

			if (item.BroadcastType == BroadcastType.Automatically && !string.IsNullOrEmpty(dictionary["EndDate"].ToString()) && !string.IsNullOrEmpty(dictionary["EndTime"].ToString()))
			{
				item.EndDateTime = DateTime.Parse(string.Format("{0} {1}", dictionary["EndDate"], dictionary["EndTime"]));
			}

			var teamDocumentsUrls = item.VideoContentType == VideoContentType.PaidGroups ? "TeamDocumentsUrlsPaidGroups" : "TeamDocumentsUrlsPaid";
			var teamDocumentsNames = item.VideoContentType == VideoContentType.PaidGroups ? "TeamDocumentsNamesPaidGroups" : "TeamDocumentsNamesPaid";

            if (!string.IsNullOrEmpty(dictionary[teamDocumentsUrls].ToString()))
			{
				item.TeamDocumentsUrls.AddRange(dictionary[teamDocumentsUrls].ToString().Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries));
			}

            if (!string.IsNullOrEmpty(dictionary[teamDocumentsNames].ToString()))
			{
				item.TeamDocumentsNames.AddRange(dictionary[teamDocumentsNames].ToString().Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries));
			}

			if (!string.IsNullOrEmpty(dictionary["Tags"].ToString()))
			{
				item.Tags.AddRange(dictionary["Tags"].ToString().Split(new[] { ";", "," }, StringSplitOptions.RemoveEmptyEntries));
			}

            if (!string.IsNullOrEmpty(dictionary["Price"].ToString()))
            {
                item.Price = decimal.Parse(dictionary["Price"].ToString(), cinfo);
            }
            else
                item.Price = 0;

			if (!string.IsNullOrEmpty(dictionary["TeamCount"].ToString()))
			{
				item.TeamCount = short.Parse(dictionary["TeamCount"].ToString());
			}

			if (string.IsNullOrEmpty(item.ThumbnailFileUrl))
			{
				switch (item.VideoContentType)
				{
					case VideoContentType.Free:
						item.ThumbnailFileUrl = "~/Upload/OnlineContent/default_icon_video_type_my.png";
						break;
					case VideoContentType.Paid:
						item.ThumbnailFileUrl = "~/Upload/OnlineContent/default_icon_video_type_conference.png";
						break;
					case VideoContentType.PaidGroups:
						item.ThumbnailFileUrl = "~/Upload/OnlineContent/default_icon_video_type_meeting.png";
						break;
				}
			}

			return item;
		}

		public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
		{
			var item = obj as OnlineContent;
			var result = new Dictionary<string, object>();
			var builder = new StringBuilder();
            CultureInfo newc = (CultureInfo)CultureInfo.CurrentCulture.Clone();
            newc.NumberFormat.NumberDecimalSeparator = ".";
            Thread.CurrentThread.CurrentCulture = newc;
            if (item != null)
			{
                result.Add("QualityString", item.QualityString);
                result.Add("ViewrCnt", item.MaxUsers);
                result.Add("MaxTime", item.MaxHours);
                //
                result.Add("QualityStringCost",0);
                result.Add("ViewrCntCost",0);
                result.Add("MaxTimeMult",0);
                result.Add("ContentTypeMult",0);
                //
				result.Add("Name", item.Title);
				result.Add("Description", item.Description);
				result.Add("SelectedCulture", item.Culture);
				result.Add("SelectedCountry", item.CountryId);
				result.Add("VideoContentType", item.VideoContentType.ToString());
				result.Add("Price", item.MinimalPrice.HasValue ? item.MinimalPrice.ToString() : "0");
				result.Add("Password", string.IsNullOrEmpty(item.Password) ? "" : item.Password);
				result.Add("Categories", string.Join(";", item.OnlineCategorizations.Select(x => x.CategoryId.ToString())));
				result.Add("ThumbnailFileName", "Thumbnail file");
				result.Add("ThumbnailFileUrl", item.ImageUrl);
				result.Add("Tags", item.OnlineContentTags.Any() ? string.Join(";", item.OnlineContentTags.Select(x => x.Tag.Name.ToString())) : string.Empty);
				result.Add("CamParam", "");
				result.Add("BroadcastType", item.BroadcastType == 1 ? "selfBroadcast" : "timeBroadcast");
				result.Add("BroadcastDescription", item.BroadcastDescription);
				result.Add("ManualStartDate", item.BroadcastType == 1 ? item.BroadcastStart.Value.Date.ToString("dd MMMM yyyy") : "");
				result.Add("StartDate", item.BroadcastType == 2 ? item.BroadcastStart.Value.Date.ToString("dd MMMM yyyy") : "");
				result.Add("EndDate", item.BroadcastType == 2 ? item.BroadcastEnd.Value.Date.ToString("dd MMMM yyyy") : "");
				result.Add("ManualStartTime", item.BroadcastType == 1 ? string.Format("{0:t}", item.BroadcastStart.Value) : "");
				result.Add("StartTime", item.BroadcastType == 2 ? string.Format("{0:t}", item.BroadcastStart.Value) : "");
				result.Add("EndTime", item.BroadcastType == 3 ? string.Format("{0:t}", item.BroadcastEnd.Value) : "");
				result.Add("TeamCount", item.TeamCount);
				result.Add("TeamDocumentsUrlsPaid", "");
				result.Add("TeamDocumentsUrlsPaidGroups", "");
				result.Add("TeamDocumentsNamesPaid", "");
				result.Add("TeamDocumentsNamesPaidGroups", "");
				result.Add("TeamDocumentsListHtmlPaid", "");
				result.Add("TeamDocumentsListHtmlPaidGroups", "");

				if (item.VideoContentType == VideoContentType.Paid)
				{
					result["TeamDocumentsUrlsPaid"] = string.Join(";", item.TeamDocs.OrderBy(x => x.Name).Select(x => x.Url));
					result["TeamDocumentsNamesPaid"] = string.Join(";", item.TeamDocs.OrderBy(x => x.Name).Select(x => x.Name));
					builder.Clear();
					foreach (var name in item.TeamDocs.OrderBy(x => x.Name).Select(x => x.Name))
					{
						builder.AppendFormat("<li>{0}</li>", name);
					}
					result["TeamDocumentsListHtmlPaid"] = builder.ToString();
				}
				else if (item.VideoContentType == VideoContentType.PaidGroups)
				{
					result["TeamDocumentsUrlsPaidGroups"] = string.Join(";", item.TeamDocs.OrderBy(x => x.Name).Select(x => x.Url));
					result["TeamDocumentsNamesPaidGroups"] = string.Join(";", item.TeamDocs.OrderBy(x => x.Name).Select(x => x.Name));
					builder.Clear();
					foreach (var name in item.TeamDocs.OrderBy(x => x.Name).Select(x => x.Name))
					{
						builder.AppendFormat("<li>{0}</li>", name);
					}
					result["TeamDocumentsListHtmlPaidGroups"] = builder.ToString();
				}

				result.Add("IsMeetingPaid", item.VideoContentType == VideoContentType.PaidGroups);
				result.Add("IsDraft", item.IsDraft);
				result.Add("AutoHistory", item.AutoHistory.HasValue && item.AutoHistory.Value);
				result.Add("CreatedContentId", item.Id);
			}

			return result;
		}
	}
}